package com.summer.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.summer.entity.OrderRepayment;
import com.summer.mapper.OrderRepaymentDetailDAO;
import com.summer.mapper.OrderRepaymentMapper;
import com.summer.service.IOrderRepaymentService;
import com.summer.util.BuildXLSX;
import com.summer.util.CallBackResult;
import com.summer.util.Constant;
import com.summer.util.XlsxParam;
import com.summer.vo.PaymentDetailUserVO;
import com.summer.vo.PaymentUserVO;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Desc:
 * Created by tl on 2019/1/2
 */
@Controller
@RequestMapping("/v1.0/api/repaymentOrder")
public class OrderRepaymentController {
    private static Logger log = LoggerFactory.getLogger(OrderRepaymentController.class);
    @Resource
    private OrderRepaymentMapper orderRepaymentMapper;
    @Resource
    private IOrderRepaymentService orderRepaymentService;
    @Resource
    private OrderRepaymentDetailDAO orderRepaymentDetailDAO;

    /**
     * 待还记录列表
     *
     * @param jsonData
     * @return
     */
    @ResponseBody
    @PostMapping("/queryToPay")
    public String queryToPay(@RequestBody String jsonData) {
        Map<String, Object> params = JSONObject.parseObject(jsonData);
        log.info("OrderRepaymentController queryToPay params=" + params.toString());
        PageHelper.startPage(params);
        params.put("toPay", "true");
        List<PaymentUserVO> list = orderRepaymentMapper.findParams(params);
        handleRepaymentType(list);
        return CallBackResult.returnJson(new PageInfo<>(list));
    }

    /**
     * 已还记录列表
     *
     * @param jsonData
     * @return
     */
    @ResponseBody
    @PostMapping("/queryPaid")
    public String queryPaid(@RequestBody String jsonData) {
        Map<String, Object> params = JSONObject.parseObject(jsonData);
        log.info("OrderRepaymentController queryPaid params=" + params.toString());
        PageHelper.startPage(params);
        List<PaymentDetailUserVO> list = orderRepaymentDetailDAO.findParams(params);
        return CallBackResult.returnJson(new PageInfo<>(list));
    }

    /**
     * 线下还款
     *
     * @param jsonData
     * @return
     */
    @ResponseBody
    @PostMapping("/offlinePay")
    public String offlinePay(@RequestBody String jsonData) {
        Map<String, Object> params = JSONObject.parseObject(jsonData);
        log.info("OrderRepaymentController offlinePay params=" + params.toString());
        OrderRepayment orderRepayment = checkId(params);
        if (null == orderRepayment)
            return CallBackResult.returnJson(CallBackResult.BUSINESS_ERROR, "参数非法");
        Object paidAmountObj = params.get("paidAmount");
        Object payTimeObj = params.get("payTime");
        String remark = params.get("remark") == null ? "" : params.get("remark").toString();
        String thirdOrderNo = params.get("thirdOrderNo") == null ? "" : params.get("thirdOrderNo").toString();
        Object payTypeObj = params.get("payType");
        if (null == paidAmountObj)
            return CallBackResult.returnJson(CallBackResult.BUSINESS_ERROR, "参数非法");
        int paidAmount = Integer.parseInt(paidAmountObj.toString());
        if (paidAmount <= 0 || paidAmount > (orderRepayment.getRepaymentAmount() - orderRepayment.getPaidAmount()) * 100)
            return CallBackResult.returnJson(CallBackResult.BUSINESS_ERROR, "还款金额必须大于0且小于应还金额");
        orderRepaymentService.payOffline(orderRepayment, payTimeObj, remark, thirdOrderNo, payTypeObj, paidAmount);
        return CallBackResult.returnJson("操作成功");
    }


    private OrderRepayment checkId(Map<String, Object> params) {
        Object idObj = params.get("id");
        if (null == idObj) {
            return null;
        }
        return orderRepaymentMapper.selectByPrimaryKey(Integer.parseInt(idObj.toString()));
    }

    private void handleRepaymentType(List<PaymentUserVO> list) {
        if (CollectionUtils.isNotEmpty(list)) {
            for (PaymentUserVO paymentUserVO : list) {
                if (paymentUserVO == null) {
                    continue;
                }
                Integer overdueCount = paymentUserVO.getOverdueCount();
                Integer renewalCount = paymentUserVO.getRenewalCount();
                paymentUserVO.setRepaymentType(Constant.REPAYMENT_TYPE_NORMAL);
                if (renewalCount > 0) {
                    paymentUserVO.setRepaymentType(Constant.REPAYMENT_TYPE_RENEWAL);
                }
                if (overdueCount > 0) {
                    paymentUserVO.setRepaymentType(Constant.REPAYMENT_TYPE_OVERDUE);
                }
            }
        }
    }

    /**
     * 导出待还订单列表
     *
     * @param request
     * @param response
     * @param params
     * @throws Exception
     */
    @RequestMapping("downloadOrderRepayment")
    public void downloadOrderRepayment(HttpServletRequest request, HttpServletResponse response,
                                       @RequestParam Map<String, Object> params) throws Exception {
        log.info("OrderRepaymentController downloadOrderRepayment params=" + params.toString());
        List<PaymentUserVO> list = orderRepaymentMapper.findParams(params);
        handleRepaymentType(list);
        log.info("OrderRepaymentController downloadOrderRepayment size=" + list.size());
        String title = "待还订单列表";
        BuildXLSX.setFileDownloadHeader(request, response, title);
        LinkedHashMap<String, String> titleMap = new LinkedHashMap<>();
        titleMap.put("repaymentTimeChg", "应还款时间");
        titleMap.put("realName", "客户姓名");
        titleMap.put("phone", "手机号码");
        titleMap.put("repaymentAmount", "应还金额");

        titleMap.put("loanTerm", "借款期限");
        titleMap.put("repaymentInterval", "距离还款日");
        titleMap.put("repaymentType", "待还类型");
        titleMap.put("renewalCount", "展期次数");
        titleMap.put("overdueCount", "逾期次数");
        titleMap.put("outTradeNo", "订单号");
        titleMap.put("reviewer", "审核人");
        XlsxParam xlsxParam = new XlsxParam(list, title, titleMap);
        OutputStream os = response.getOutputStream();
        BuildXLSX.buildExcel(xlsxParam, os);
    }

    /**
     * 导出已还订单列表
     *
     * @param request
     * @param response
     * @param params
     * @throws Exception
     */
    @RequestMapping("downloadOrderPaid")
    public void downloadOrderPaid(HttpServletRequest request, HttpServletResponse response,
                                  @RequestParam Map<String, Object> params) throws Exception {
        log.info("OrderRepaymentController downloadOrderPaid params=" + params.toString());
        List<PaymentDetailUserVO> list = orderRepaymentDetailDAO.findParams(params);
        log.info("OrderRepaymentController downloadOrderPaid size=" + list.size());
        String title = "已还订单列表";
        BuildXLSX.setFileDownloadHeader(request, response, title);
        LinkedHashMap<String, String> titleMap = new LinkedHashMap<>();
        titleMap.put("payTimeChg", "实际还款时间");
        titleMap.put("realName", "客户姓名");
        titleMap.put("phone", "手机号码");
        titleMap.put("repaymentAmount", "应还金额");

        titleMap.put("loanTerm", "借款期限");
        titleMap.put("repaymentTime", "应还时间");
        titleMap.put("paidAmount", "实际还款金额");
        titleMap.put("status", "还款状态");
        titleMap.put("payTip", "失败原因");
        titleMap.put("payType", "支付方式");
        titleMap.put("overdue", "还款类型");
        titleMap.put("overdueCount", "逾期次数");
        titleMap.put("forwardCount", "提前还款次数");
        titleMap.put("thirdOrderNo", "订单号");
        titleMap.put("reviewer", "审核人");
        XlsxParam xlsxParam = new XlsxParam(list, title, titleMap);
        OutputStream os = response.getOutputStream();
        BuildXLSX.buildExcel(xlsxParam, os);
    }
}
